package com.example.book.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.example.book.mapper.ChapterMapper;
import com.example.book.service.ChapterTaskService;
import com.example.common.enums.ScheduleConstants;
import com.example.common.enums.TaskTypeEnum;
import com.example.schedule.entity.dto.Task;
import com.example.schedule.service.TaskService;
import com.example.utils.SnowflakeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
@Slf4j
public class ChapterTaskServiceImpl implements ChapterTaskService {

    @Autowired
    private TaskService taskService;
    @Autowired
    private ChapterMapper chapterMapper;
/**
     * 添加任务到延迟队列中
     *
     * @param id          章节id
     * @param publishTime 发布时间  可以作为任务的执行时间*/


    @Override
    @Async
    public void addNewsToTask(Long id, Date publishTime) {

        log.info("添加任务到延迟服务中------begin");

        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setParameters(id);
        task.setTaskId(SnowflakeGenerator.generate());
        taskService.addTask(task);

        log.info("添加任务到延迟服务中------end");
    }

/**
     * 消费任务,审核章节*/


    //每一秒钟去拉取任务
    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewsBtTask() {
        Task task = taskService.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (!ObjectUtil.isNull(task)){
            log.info("消费任务,审核文章");
            //通过审核,修改文章状态
            int i = chapterMapper.updateStatusById(ScheduleConstants.EXECUTED,task.getParameters());
            if (i > 0){
                log.info("审核文章成功");
            }

        }
    }
}
